import fs from 'fs'

// 解析带文件头的OPUS格式（参考app.js的实现）
export function parseOpusFileWithHeader(data) {
    const view = new DataView(data.buffer);

    // 检查 "OpusHead" 标识
    const opusHead = String.fromCharCode(...data.slice(0, 8));
    if (opusHead !== "OpusHead") {
        throw new Error("不是有效的OPUS文件格式");
    }

    let offset = 8;

    // 读取版本号
    const version = data[offset++];
    console.log(`OPUS文件版本: ${version}`);

    // 读取通道数
    const channels = data[offset++];
    console.log(`通道数: ${channels}`);

    // 读取预跳过样本数
    const preSkip = view.getUint16(offset, true);
    offset += 2;
    console.log(`预跳过样本数: ${preSkip}`);

    // 读取采样率
    const sampleRate = view.getUint32(offset, true);
    offset += 4;
    console.log(`采样率: ${sampleRate}Hz`);

    // 读取输出增益
    const outputGain = view.getUint16(offset, true);
    offset += 2;
    console.log(`输出增益: ${outputGain}`);

    // 读取通道映射
    const channelMapping = data[offset++];
    console.log(`通道映射: ${channelMapping}`);

    // 读取自定义扩展信息
    const frameSize = view.getUint16(offset, true);
    offset += 2;
    console.log(`帧大小: ${frameSize}`);

    const totalFrames = view.getUint32(offset, true);
    offset += 4;
    console.log(`总帧数: ${totalFrames}`);

    // 读取所有OPUS帧
    const opusFrames = [];
    for (let i = 0; i < totalFrames; i++) {
        if (offset + 4 > data.length) break;

        const frameLength = view.getUint32(offset, true);
        offset += 4;

        if (offset + frameLength > data.length) break;

        const frameData = data.slice(offset, offset + frameLength);
        opusFrames.push(frameData);
        offset += frameLength;
    }

    console.log(`成功解析 ${opusFrames.length} 帧OPUS数据`);
    return opusFrames;
}

// 保存原始OPUS数据帧到文件
export function saveOpusFramesToFile(opusFrames, outputPath = "raw_opus_frames.opus") {
    try {
        // 计算总大小
        const totalSize = opusFrames.reduce((total, frame) => total + frame.length, 0);
        
        // 创建ArrayBuffer来存储所有帧数据
        const buffer = new ArrayBuffer(totalSize);
        const uint8Array = new Uint8Array(buffer);
        
        let offset = 0;
        
        // 将所有帧数据写入buffer
        for (const frame of opusFrames) {
            uint8Array.set(frame, offset);
            offset += frame.length;
        }
        
        // 保存到文件
        fs.writeFileSync(outputPath, uint8Array);
        
        console.log(`成功保存 ${opusFrames.length} 个原始OPUS帧到文件: ${outputPath}`);
        console.log(`文件大小: ${totalSize} 字节`);
        console.log(`平均每帧大小: ${Math.round(totalSize / opusFrames.length)} 字节`);
        
        return outputPath;
        
    } catch (error) {
        console.error('保存OPUS帧失败:', error);
        throw error;
    }
}

// 解析并保存OPUS帧的便捷函数
export function parseAndSaveOpusFrames(data, outputPath = "raw_opus_frames.opus") {
    try {
        console.log("=== 开始解析OPUS帧 ===");
        
        // 解析OPUS文件
        const opusFrames = parseOpusFileWithHeader(data);
        
        // 如果指定了输出路径，则保存原始帧数据
        let savedPath = null;
        if (outputPath) {
            savedPath = saveOpusFramesToFile(opusFrames, outputPath);
            console.log("=== 解析并保存完成 ===");
        } else {
            console.log("=== 解析完成（未保存原始文件）===");
        }
        
        return {
            frames: opusFrames,
            savedPath: savedPath,
            frameCount: opusFrames.length
        };
        
    } catch (error) {
        console.error('解析OPUS帧失败:', error);
        throw error;
    }
}